/**
 * 此脚本用于生成临时的音效文件
 * 因为我们不能直接下载外部音效，所以使用Web Audio API创建简单的音效
 */

// 创建音频上下文
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

// 创建音频数据并下载为文件
function generateAndDownload(audioBuffer, filename) {
  // 将AudioBuffer转换为WAV格式
  const wavData = audioBufferToWav(audioBuffer);
  const blob = new Blob([wavData], { type: 'audio/wav' });
  
  // 创建下载链接
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  
  // 清理
  URL.revokeObjectURL(url);
}

// 生成揭晓音效
function generateRevealSound() {
  const duration = 1.0;
  const buffer = audioContext.createBuffer(1, audioContext.sampleRate * duration, audioContext.sampleRate);
  const channel = buffer.getChannelData(0);
  
  for (let i = 0; i < buffer.length; i++) {
    // 创建上升的音调
    const t = i / buffer.length;
    const frequency = 220 + 880 * t;
    channel[i] = 0.5 * Math.sin(2 * Math.PI * frequency * t);
    
    // 应用淡入淡出效果
    const fadeTime = 0.1;
    if (t < fadeTime) {
      channel[i] *= t / fadeTime;
    } else if (t > 1 - fadeTime) {
      channel[i] *= (1 - t) / fadeTime;
    }
  }
  
  generateAndDownload(buffer, 'reveal.mp3');
}

// 生成掌声音效
function generateApplauseSound() {
  const duration = 3.0;
  const buffer = audioContext.createBuffer(1, audioContext.sampleRate * duration, audioContext.sampleRate);
  const channel = buffer.getChannelData(0);
  
  for (let i = 0; i < buffer.length; i++) {
    // 模拟掌声的随机噪声
    const t = i / buffer.length;
    channel[i] = (Math.random() * 2 - 1) * 0.5;
    
    // 掌声强度随时间变化
    const envelope = Math.min(t * 3, 1) * Math.pow(1 - t, 0.5);
    channel[i] *= envelope;
  }
  
  generateAndDownload(buffer, 'applause.mp3');
}

// 生成whoosh音效
function generateWhooshSound() {
  const duration = 0.8;
  const buffer = audioContext.createBuffer(1, audioContext.sampleRate * duration, audioContext.sampleRate);
  const channel = buffer.getChannelData(0);
  
  for (let i = 0; i < buffer.length; i++) {
    const t = i / buffer.length;
    // 白噪声 + 高频滤波
    channel[i] = (Math.random() * 2 - 1) * Math.pow(1 - t, 2) * 0.8;
  }
  
  generateAndDownload(buffer, 'whoosh.mp3');
}

// 生成史诗音效
function generateEpicSound() {
  const duration = 5.0;
  const buffer = audioContext.createBuffer(1, audioContext.sampleRate * duration, audioContext.sampleRate);
  const channel = buffer.getChannelData(0);
  
  // 创建低音鼓声音
  for (let i = 0; i < buffer.length; i++) {
    const t = i / buffer.length;
    
    // 主旋律
    const baseFreq = 110; // A2音符
    const note1 = Math.sin(2 * Math.PI * baseFreq * t);
    const note2 = Math.sin(2 * Math.PI * (baseFreq * 5/4) * t) * 0.5;
    const note3 = Math.sin(2 * Math.PI * (baseFreq * 3/2) * t) * 0.3;
    
    // 混合音符
    channel[i] = (note1 + note2 + note3) / 3;
    
    // 添加脉冲效果
    const pulseRate = 2; // 每秒脉冲次数
    const pulse = Math.pow(Math.sin(2 * Math.PI * pulseRate * t) * 0.5 + 0.5, 2);
    channel[i] *= 0.6 + pulse * 0.4;
    
    // 应用淡入淡出
    if (t < 0.1) {
      channel[i] *= t / 0.1;
    } else if (t > 0.9) {
      channel[i] *= (1 - t) / 0.1;
    }
  }
  
  generateAndDownload(buffer, 'epic.mp3');
}

// 生成点击音效
function generateClickSound() {
  const duration = 0.15;
  const buffer = audioContext.createBuffer(1, audioContext.sampleRate * duration, audioContext.sampleRate);
  const channel = buffer.getChannelData(0);
  
  for (let i = 0; i < buffer.length; i++) {
    const t = i / buffer.length;
    // 简单的衰减正弦波
    channel[i] = Math.sin(2 * Math.PI * 1000 * t) * Math.exp(-15 * t);
  }
  
  generateAndDownload(buffer, 'click.mp3');
}

// 生成所有音效
function generateAllSounds() {
  generateRevealSound();
  setTimeout(generateApplauseSound, 1000);
  setTimeout(generateWhooshSound, 2000);
  setTimeout(generateEpicSound, 3000);
  setTimeout(generateClickSound, 4000);
}

// 将AudioBuffer转换为WAV格式
function audioBufferToWav(buffer) {
  const numChannels = buffer.numberOfChannels;
  const sampleRate = buffer.sampleRate;
  const format = 1; // PCM
  const bitDepth = 16;
  
  const bytesPerSample = bitDepth / 8;
  const blockAlign = numChannels * bytesPerSample;
  
  const dataLength = buffer.length * numChannels * bytesPerSample;
  const bufferLength = 44 + dataLength;
  
  const arrayBuffer = new ArrayBuffer(bufferLength);
  const view = new DataView(arrayBuffer);
  
  // RIFF identifier
  writeString(view, 0, 'RIFF');
  // file length - 8
  view.setUint32(4, 36 + dataLength, true);
  // RIFF type
  writeString(view, 8, 'WAVE');
  // format chunk identifier
  writeString(view, 12, 'fmt ');
  // format chunk length
  view.setUint32(16, 16, true);
  // sample format (raw)
  view.setUint16(20, format, true);
  // channel count
  view.setUint16(22, numChannels, true);
  // sample rate
  view.setUint32(24, sampleRate, true);
  // byte rate (sample rate * block align)
  view.setUint32(28, sampleRate * blockAlign, true);
  // block align (channel count * bytes per sample)
  view.setUint16(32, blockAlign, true);
  // bits per sample
  view.setUint16(34, bitDepth, true);
  // data chunk identifier
  writeString(view, 36, 'data');
  // data chunk length
  view.setUint32(40, dataLength, true);
  
  // 写入音频数据
  const offset = 44;
  const channelData = [];
  for (let i = 0; i < numChannels; i++) {
    channelData.push(buffer.getChannelData(i));
  }
  
  let pos = offset;
  for (let i = 0; i < buffer.length; i++) {
    for (let c = 0; c < numChannels; c++) {
      const sample = Math.max(-1, Math.min(1, channelData[c][i]));
      const value = (sample < 0 ? sample * 0x8000 : sample * 0x7FFF);
      view.setInt16(pos, value, true);
      pos += 2;
    }
  }
  
  return new Uint8Array(arrayBuffer);
}

function writeString(view, offset, string) {
  for (let i = 0; i < string.length; i++) {
    view.setUint8(offset + i, string.charCodeAt(i));
  }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
  const container = document.createElement('div');
  container.style.fontFamily = 'Arial, sans-serif';
  container.style.maxWidth = '600px';
  container.style.margin = '20px auto';
  container.style.padding = '20px';
  container.style.backgroundColor = '#f8f9fa';
  container.style.borderRadius = '8px';
  container.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
  
  const title = document.createElement('h1');
  title.textContent = '音效生成工具';
  title.style.color = '#3a6ea5';
  title.style.marginTop = '0';
  
  const description = document.createElement('p');
  description.textContent = '点击下面的按钮生成项目所需的各种音效文件。这些文件将自动下载到您的设备上。';
  
  const button = document.createElement('button');
  button.textContent = '生成所有音效';
  button.style.backgroundColor = '#3a6ea5';
  button.style.color = 'white';
  button.style.border = 'none';
  button.style.padding = '10px 20px';
  button.style.borderRadius = '4px';
  button.style.cursor = 'pointer';
  button.style.fontSize = '16px';
  button.style.marginTop = '20px';
  button.onclick = generateAllSounds;
  
  const note = document.createElement('p');
  note.textContent = '注意：请在下载完成后，将这些音效文件移动到项目的 public/sounds 目录中。';
  note.style.marginTop = '20px';
  note.style.fontSize = '14px';
  note.style.color = '#666';
  
  container.appendChild(title);
  container.appendChild(description);
  container.appendChild(button);
  container.appendChild(note);
  
  document.body.appendChild(container);
}); 